package sto.orz.webapp.result;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sto.orz.json.JSONAdapter;

import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.Result;

public class JsonResult implements Result {
	private static final long serialVersionUID = -8388465236669056015L;
	private static final Log log = LogFactory.getLog(JsonResult.class);
	JSONAdapter json;
	boolean jsonSet = false;

	// FIXME socket write error
	// [java] 2006-12-12 14:54:24 org.apache.catalina.core.StandardHostValve
	// status
	// [java] 警告: Exception Processing ErrorPage[errorCode=404,
	// location=/404.jsp]
	// [java] ClientAbortException: java.net.SocketException: Software caused
	// connection abort: socket write error
	// [java] at
	// org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:327)
	public void execute(ActionInvocation invocation) throws Exception {
//		long startTime = System.currentTimeMillis();
		JSONAdapter json = null;

		if (jsonSet) {
			json = this.json;
		} else {
			json = (JSONAdapter) invocation.getStack().findValue("json");
		}

		if (json == null) {
			throw new NullPointerException("No json found");
		}

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/javascript; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");

		String result = json.toJson();

		PrintWriter writer = response.getWriter();
		writer.write(result);
		writer.flush();
		//writer.close();
		// if (log.isDebugEnabled()) {
		// log.debug("Time:" + (System.currentTimeMillis() - startTime)
		// + "ms");
		// }
	}

	public void setJson(JSONAdapter json) {
		this.json = json;
		jsonSet = true;
	}
}
